import React, { useEffect, useMemo, useState } from 'react';
import {
  Card,
  Descriptions,
  Divider,
  Grid,
  Space,
  Skeleton, Tabs
} from '@arco-design/web-react';

const { Row, Col } = Grid;
import useLocale from '@/utils/useLocale';
import { useLocation } from 'react-router';
import instance from '@/utils/request';
import { ParameterRecord } from '@/pages/equipment/parameter';
import RuntimePanel from './RuntimePanel';
import ProducePanel from './ProducePanel';
import MonitorPanel from './MonitorPanel';
import AlarmRecordPanel from '@/pages/monitor/device/AlarmRecordPanel';
import RealtimePanel from '@/pages/monitor/device/RealtimePanel';
import { resolveDeviceActivateState, resolveDeviceRunningState, resolveEnabledName } from '@/constants/functions';
import { DeviceResponse } from '@/constants/type';
import OeePanel from '@/pages/monitor/device/OeePanel';
import UtilizationPanel from '@/pages/monitor/device/UtilizationPanel';

const locale = {
  'en-US': {},
  'zh-CN': {
    'basic.title': '设备基本信息',
    'basic.code': '设备编码',
    'basic.enabled': '是否启用',
    'basic.remark': '设备备注',
    'basic.type': '设备类型',
    'basic.model': '物模型',
    'basic.structure': '工厂结构',
    'realtime.title': '实时信息',
    'runtime.title': '运行信息',
    'runtime.runningState': '运行状态',
    'runtime.activateState': '激活状态',
    'parameter.title': '设备参数信息',
    'oee.title': 'OEE',
    'utilization.title': '稼动率',
    'produce.title': '产量信息',
    'monitor.title': '参数监控',
    'alarm_record.title': '报警记录'
  }
};

export default () => {
  const t = useLocale(locale);
  const location = useLocation();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<DeviceResponse>();
  const [basicData, setBasicData] = useState([]);
  const [runtimeData, setRuntimeData] = useState([]);
  const [deviceParameters, setDeviceParameters] = useState<ParameterRecord[]>([]);
  const deviceMonitorParameters = useMemo(() => {
    return deviceParameters.filter(it => (it.abilities || []).includes('MONITOR'));
  }, [deviceParameters]);

  function fetchDeviceDetail(id: number) {
    setLoading(true);
    instance
      .post('/api/device/get', { id: id })
      .then((res) => {
        if (res.data.code === 200) {
          const device = res.data.data;
          setData(device);
          const basicOptions = [];
          const runtimeOptions = [];
          basicOptions.push({
            label: t['basic.code'],
            value: device.code
          });
          basicOptions.push({
            label: t['basic.enabled'],
            value: resolveEnabledName(device?.enabled)
          });
          basicOptions.push({
            label: t['basic.remark'],
            value: device?.remark
          });
          basicOptions.push({
            label: t['basic.type'],
            value: device?.type?.name
          });
          basicOptions.push({
            label: t['basic.model'],
            value: device?.model?.name
          });
          basicOptions.push({
            label: t['basic.structure'],
            value: device?.structure?.name
          });
          runtimeOptions.push({
            label: t['runtime.runningState'],
            value: resolveDeviceRunningState(device?.runningState)
          });
          runtimeOptions.push({
            label: t['runtime.activateState'],
            value: resolveDeviceActivateState(device?.activateState)
          });
          setBasicData(basicOptions);
          setRuntimeData(runtimeOptions);
          const resolveAllParameters = (current) => {
            const parameters = [];
            if (!current) {
              return parameters;
            }
            current?.parameters?.forEach((item) => {
              parameters.push(item);
            });
            (current?.children || []).forEach((item) => {
              resolveAllParameters(item).forEach(it => parameters.push(it));
            });
            return parameters;
          };
          const totalParameters = resolveAllParameters(device?.model);
          setDeviceParameters(totalParameters);
        }
      })
      .finally(() => {
        setLoading(false);
      });
  }

  useEffect(() => {
    const search = new URLSearchParams(location.search);
    const id = search.get('id');
    if (!!id) {
      fetchDeviceDetail(parseInt(id));
    }
  }, []);

  return (
    <Space style={{ width: '100%' }} direction="vertical">
      <Card title={data?.name}>
        <Row>
          <Col span={24}>
            {!!loading ? (
              <Skeleton animation />
            ) : (
              <>
                <Row>
                  <Col flex={2}>
                    <Descriptions colon=" :" layout="inline-horizontal" title={t['basic.title']} data={basicData} />
                  </Col>
                  <Divider type="vertical" />
                  <Col flex={1}>
                    <Descriptions colon=" :" layout="inline-horizontal" title={t['runtime.title']} data={runtimeData} />
                  </Col>
                </Row>
              </>
            )}
          </Col>
        </Row>
      </Card>
      <Tabs defaultActiveTab="realtime">
        <Tabs.TabPane key="realtime" title={t['realtime.title']} destroyOnHide>
          {!!!loading && <RealtimePanel id={data?.id} parameters={deviceMonitorParameters} />}
        </Tabs.TabPane>
        <Tabs.TabPane key="runtime" title={t['runtime.title']}>
          <RuntimePanel id={data?.id} />
        </Tabs.TabPane>
        <Tabs.TabPane key="oee" title={t['oee.title']} destroyOnHide>
          <OeePanel id={data?.id} />
        </Tabs.TabPane>
        <Tabs.TabPane key="utilization" title={t['utilization.title']} destroyOnHide>
          <UtilizationPanel id={data?.id} />
        </Tabs.TabPane>
        <Tabs.TabPane key="produce" title={t['produce.title']}>
          <ProducePanel id={data?.id} />
        </Tabs.TabPane>
        <Tabs.TabPane key="monitor" title={t['monitor.title']}>
          {!!!loading && <MonitorPanel id={data?.id} parameters={deviceMonitorParameters} />}
        </Tabs.TabPane>
        <Tabs.TabPane key="alarm_record" title={t['alarm_record.title']}>
          <AlarmRecordPanel id={data?.id} />
        </Tabs.TabPane>
      </Tabs>
    </Space>
  );

}